import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tag, Button, message, Empty, Spin, Modal, Table, Space, Input } from 'antd';
import axios from 'axios';
import { ClockCircleOutlined, EnvironmentOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons';

const { Title, Paragraph } = Typography;

// 定义活动接口
interface Activity {
  id: number;
  club_id: number;
  title: string;
  type: string | null;
  description: string | null;
  location: string | null;
  start_time: string;
  end_time: string;
  signup_deadline: string;
  max_participants: number | null;
  points: string;
  created_at: string;
}

// Modify Activity interface to include registration status and studentActivityId
interface ActivityWithStatus extends Activity {
  isRegistered?: boolean; // Optional property to track registration status
  studentActivityId?: number; // Optional property to store student_activity record ID
}

// Define interface for registered student information
interface RegisteredStudent {
  id: number; // student_activity record ID
  student_id: number; // student ID
  register_time: string; // registration timestamp
  student_name: string; // student name (fetched from /api/getStudentById)
  student_no: string; // student number (fetched from /api/getStudentById)
}

// Define Pagination interface (if used by the API)
// interface Pagination {
//   current: number;
//   pageSize: number;
//   total: number;
//   totalPages: number;
// }

// Define API Response interface
// interface ApiResponse {
//   success: boolean;
//   message: string;
//   data: {
//     activities: Activity[];
//     pagination: Pagination;
//   };
// }

const JoinActivityPage: React.FC = () => {
  // Use the new interface for activities state
  const [activities, setActivities] = useState<ActivityWithStatus[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // State for registered students modal
  const [isRegisteredStudentsModalVisible, setIsRegisteredStudentsModalVisible] = useState(false);
  const [registeredStudents, setRegisteredStudents] = useState<RegisteredStudent[]>([]);
  const [registeredStudentsLoading, setRegisteredStudentsLoading] = useState(false);
  const [selectedActivityTitle, setSelectedActivityTitle] = useState(''); // To show activity title in modal
  // State for filtering
  const [filterKeyword, setFilterKeyword] = useState('');

  useEffect(() => {
    fetchActivities();
  }, []);

  const fetchActivities = async () => {
    try {
      setLoading(true);
      setError(null);

      // 获取当前登录学生的 ID
      const userInfo = localStorage.getItem('userInfo');
      let studentId: number | null = null; // Explicitly declare the type
      if (userInfo) {
        try {
          studentId = JSON.parse(userInfo).id;
        } catch (e) {
          console.error('Error parsing userInfo from localStorage:', e);
        }
      }

      if (!studentId) {
        // 如果未登录，直接获取所有活动，不检查报名状态
        console.log('User not logged in, fetching all activities without registration status check.');
        const response = await axios.get('http://localhost:5000/api/allActivity');
        if (response.data && response.data.data && Array.isArray(response.data.data.activities)) {
          setActivities(response.data.data.activities);
          message.success(response.data.message || '获取活动列表成功');
        } else {
          console.error('Unexpected response format:', response.data);
          setError('获取活动列表失败：数据格式不正确');
          message.error('获取活动列表失败：数据格式不正确');
        }
        setLoading(false);
        return;
      }

      console.log(`Fetching all activities for student ID: ${studentId}`);

      // 1. 获取所有活动列表
      const allActivitiesResponse = await axios.get('http://localhost:5000/api/allActivity');

      console.log('All Activities Response:', allActivitiesResponse.data);

      if (allActivitiesResponse.data && allActivitiesResponse.data.data && Array.isArray(allActivitiesResponse.data.data.activities)) {
        const fetchedActivities: Activity[] = allActivitiesResponse.data.data.activities;

        // 2. 检查每个活动的报名状态
        const activitiesWithStatus = await Promise.all(
          fetchedActivities.map(async (activity) => {
            try {
              // 调用新接口检查报名状态
              const registrationCheckResponse = await axios.get(
                `http://localhost:5000/api/studentActivity/${studentId}/${activity.id}`
              );

              // 如果成功找到记录且状态为 'registered'，则表示已报名
              if (registrationCheckResponse.data.success && registrationCheckResponse.data.data && registrationCheckResponse.data.data.status === 'registered') {
                return {
                  ...activity,
                  isRegistered: true,
                  studentActivityId: registrationCheckResponse.data.data.id // 存储记录 ID
                } as ActivityWithStatus; // 明确类型
              } else {
                // 如果后端返回成功但状态不是 registered，或者没有找到记录（404或其他非2xx响应），认为未报名
                return {
                  ...activity,
                  isRegistered: false,
                } as ActivityWithStatus; // 明确类型
              }
            } catch (error: any) {
              // 如果接口返回 404（未找到记录），也认为是未报名
              if (axios.isAxiosError(error) && error.response?.status === 404) {
                console.log(`Student ${studentId} not registered for activity ${activity.id}.`);
                return {
                  ...activity,
                  isRegistered: false,
                } as ActivityWithStatus; // 明确类型
              } else {
                // 其他错误，记录并视为未报名
                console.error(`Error checking registration status for activity ${activity.id}:`, error);
                return {
                  ...activity,
                  isRegistered: false,
                } as ActivityWithStatus; // 明确类型
              }
            }
          })
        );

        setActivities(activitiesWithStatus);
        message.success(allActivitiesResponse.data.message || '获取活动列表成功');

      } else {
        console.error('Unexpected response format for all activities:', allActivitiesResponse.data);
        setError('获取活动列表失败：数据格式不正确');
        message.error('获取活动列表失败：数据格式不正确');
      }
    } catch (error: any) {
      console.error('获取活动列表或检查报名状态失败:', error);
      setError(error.response?.data?.message || '获取活动列表失败');
      message.error(error.response?.data?.message || '获取活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleJoinActivity = async (activityId: number) => {
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        window.alert('请先登录才能报名活动');
        return;
      }
      const studentId = JSON.parse(userInfo).id; 

      if (!studentId) {
         window.alert('无法获取学生信息，请重新登录');
         return;
      }

      console.log(`Attempting to join activity ${activityId} with student ID ${studentId}`);

      const response = await axios.post('http://localhost:5000/api/joinActivity', {
        student_id: studentId,
        activity_id: activityId
      });
      
      console.log('Join Activity Response:', response.data);

      if (response.data.success) {
        window.alert(response.data.message || '报名成功！');
        // Update the state to reflect the successful registration
        setActivities(prevActivities => 
          prevActivities.map(activity => 
            activity.id === activityId ? { ...activity, isRegistered: true, studentActivityId: response.data.data.id } : activity // 存储新生成的记录ID
          )
        );
      } else {
        window.alert(response.data.message || '报名失败，请稍后重试');
      }
    } catch (error: any) {
      console.error('报名失败:', error);
      window.alert(error.response?.data?.message || '报名失败，请稍后重试');
    }
  };

  // Function to fetch registered students for a specific activity
  const fetchRegisteredStudents = async (activityId: number) => {
    setRegisteredStudentsLoading(true);
    try {
      // Fetch registration records by activity ID
      const response = await axios.get(`http://localhost:5000/api/activityIdregistered/${activityId}`);
      
      if (response.data.success && Array.isArray(response.data.data.records)) {
        // For each registration record, fetch student details
        const studentsWithDetails = await Promise.all(
          response.data.data.records.map(async (record: any) => {
            try {
              const studentResponse = await axios.get(`http://localhost:5000/api/getStudentById/${record.student_id}`);
              // Combine registration info with student details
              return {
                ...record, // includes id (student_activity record id), student_id, register_time
                student_name: studentResponse.data.data.name,
                student_no: studentResponse.data.data.student_no
              };
            } catch (error) {
              console.error(`获取学生信息失败 (ID: ${record.student_id}):`, error);
              return {
                ...record,
                student_name: '未知',
                student_no: '未知'
              };
            }
          })
        );
        setRegisteredStudents(studentsWithDetails);
      } else {
        console.error('获取报名记录失败或数据格式不正确:', response.data);
        message.error('获取报名学生信息失败');
        setRegisteredStudents([]); // Clear previous data on error
      }
    } catch (error) {
      console.error('获取报名学生信息失败:', error);
      message.error('获取报名学生信息失败');
      setRegisteredStudents([]); // Clear previous data on error
    } finally {
      setRegisteredStudentsLoading(false);
    }
  };

  // Function to handle filter input change
  const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFilterKeyword(e.target.value);
  };

  // Function to filter activities based on keyword
  const filteredActivities = activities.filter(activity => 
    activity.type?.toLowerCase().includes(filterKeyword.toLowerCase()) ||
    activity.title.toLowerCase().includes(filterKeyword.toLowerCase())
  );

  // Modal component to display registered students
  const RegisteredStudentsModal = () => {
    const columns = [
    //   {
    //     title: '学号',
    //     dataIndex: 'student_no',
    //     key: 'student_no',
    //   },
      {
        title: '姓名',
        dataIndex: 'student_name',
        key: 'student_name',
      },
      {
        title: '报名时间',
        dataIndex: 'register_time',
        key: 'register_time',
        render: (date: string) => new Date(date).toLocaleString(),
      },
    ];

    return (
      <Modal
        title={
          <div>
            <div>{selectedActivityTitle} - 已报名学生列表</div>
            <div style={{ fontSize: '14px', color: '#666', marginTop: '8px' }}>
              当前报名人数：{registeredStudents.length} 人
            </div>
          </div>
        }
        open={isRegisteredStudentsModalVisible}
        onCancel={() => setIsRegisteredStudentsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table
          columns={columns}
          dataSource={registeredStudents}
          rowKey="id" // Assuming the student_activity record ID is unique
          loading={registeredStudentsLoading}
          bordered
          pagination={{
            total: registeredStudents.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Modal>
    );
  };

  const formatDateTime = (dateTimeStr: string) => {
    try {
      return new Date(dateTimeStr).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (error) {
      return '无效日期';
    }
  };

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
        <p style={{ marginTop: '16px' }}>加载中...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Title level={2}>活动列表</Title>
        <Empty description={error} />
        <Button type="primary" onClick={fetchActivities} style={{ marginTop: '16px' }}>
          重试
        </Button>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>活动列表</Title>
      {/* Filter Input */}
      <div style={{ marginBottom: '16px' }}>
        <Input
          placeholder="按活动类型或标题筛选..."
          value={filterKeyword}
          onChange={handleFilterChange}
          style={{ width: 300 }}
        />
      </div>

      <Row gutter={[16, 16]}>
        {/* Use filteredActivities instead of activities */}
        {filteredActivities.length === 0 ? (
          <Col span={24}>
            <Empty description={filterKeyword ? '没有找到符合条件的活动' : '暂无活动'} />
          </Col>
        ) : (
          filteredActivities.map((activity) => (
            <Col xs={24} sm={12} md={8} lg={6} key={activity.id}>
              <Card
                hoverable
                title={activity.title}
                extra={<Tag color="blue">{activity.type || '未分类'}</Tag>}
              >
                <Paragraph ellipsis={{ rows: 2 }}>{activity.description || '暂无描述'}</Paragraph>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 开始时间：{formatDateTime(activity.start_time)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 结束时间：{formatDateTime(activity.end_time)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <ClockCircleOutlined /> 报名截止：{formatDateTime(activity.signup_deadline)}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <EnvironmentOutlined /> {activity.location || '地点待定'}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <TeamOutlined /> 截止人数：{activity.max_participants || '不限'}
                </div>
                <div style={{ marginBottom: '12px' }}>
                  <TrophyOutlined /> 可获得积分：{activity.points || '0.00'}
                </div>
                <Space>
                  <Button 
                    type="primary" 
                    block
                    onClick={() => handleJoinActivity(activity.id)}
                    // Disable button if already registered or deadline passed
                    disabled={activity.isRegistered || new Date(activity.signup_deadline) < new Date()}
                  >
                    {/* Change button text based on registration status or deadline */}
                    {activity.isRegistered ? '已报名' : (new Date(activity.signup_deadline) < new Date() ? '报名已截止' : '立即报名')}
                  </Button>
                   <Button
                    onClick={() => {
                      setSelectedActivityTitle(activity.title);
                      fetchRegisteredStudents(activity.id);
                      setIsRegisteredStudentsModalVisible(true);
                    }}
                   >
                    查看报名信息
                   </Button>
                </Space>
              </Card>
            </Col>
          ))
        )}
      </Row>
      {/* Render the modal component */}
      <RegisteredStudentsModal />
    </div>
  );
};

export default JoinActivityPage;
